import path from 'path'
import fse from 'fs-extra'
import moment from 'moment'
// const qiniu = require("qiniu");
// const upload = require('../utils/upload')
import Conf from '@/config'

class SystemService {
  static upload(origin, files) {

    const foldersRename = moment().format('YYYY_MM_DD')
    const moveFile = async (from, to) => {
      await fse.move(from, to)
    } // 移动文件
    let list = Object.values(files).reduce((arr, item, index) => {
      const {
        name,
        path: filePath,
        size,
        type
      } = item

      const fileHashName = path.basename(filePath)

      const dest = path.resolve(`public`, `${Conf.multipart.uploadDir}`, `${foldersRename}`) // 目标目录，没有没有这个文件夹会自动创建

      moveFile(filePath, dest + '/' + fileHashName)
      arr.push({
        index,
        name,
        url: `${origin}/${Conf.multipart.uploadDir}/${foldersRename}/${fileHashName}`, // 返回图片在服务器上的url地址
        abs_url: `${Conf.multipart.uploadDir}/${foldersRename}/${fileHashName}`,
        size,
        type
      })
      return arr
    }, [])
    return {
      msg: '上传成功',
      code: 200,
      data: list
    }
  }

  static async qiniu() {
    let mac = new qiniu.auth.digest.Mac(
      Conf.qiniu.accessKey,
      Conf.qiniu.secretKey
    )
    let options = {
      scope: Conf.qiniu.bucket, //要上传的空间
      expires: Conf.qiniu.expires
    }
    let putPolicy = new qiniu.rs.PutPolicy(options)
    let uploadToken = putPolicy.uploadToken(mac)
    if (uploadToken) {
      return {
        msg: '七牛云token获取成功',
        code: 200,
        data: uploadToken
      }
    }
    return {
      msg: '七牛云token获取失败',
      code: 400,
      data: null
    }
  }
}
export default SystemService